<!DOCTYPE html>
<html lang="zh-cmn-Hans">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <title>学车套餐</title>

    <!-- 微信UI库 -->
    <link rel="stylesheet" href="libs/weui/weui.css">

    <!-- 微信JS库 -->
    <script type="text/javascript" src="libs/weui.js/weui.js"></script>
    <!-- jQuery -->
    <script type="text/javascript" src="libs/jquery/jquery-2.2.3.min.js"></script>
    <!-- 微信JS-SDK -->
    <script type="text/javascript" src="libs/js-sdk/jweixin-1.2.0.js"></script>
    <!-- 自定义公共JS -->
    <script type="text/javascript" src="js/app.js"></script>
    <style>
        .weui-cells {
            margin-top: 0;
        }
        .weui-cell:before{
            left: 0;
        }
    </style>
</head>
<body>
<div class="page">

    <div class="page__bd">

        <div class="weui-cells__title" id="groupHeader"></div>
        <div class="weui-cells weui-cells_checkbox" id="list">
            <!--<label class="weui-cell weui-check__label" for="s11">
                <div class="weui-cell__bd">
                    <div style="float:left;">基础保障周末班</div>
                    <div style="float:right;">￥5800</div>
                </div>
                <div class="weui-cell__ft">
                    <input type="checkbox" class="weui-check" data-id="1" name="checkbox1" id="s11" checked="checked"/>
                    <i class="weui-icon-checked"></i>
                </div>
            </label>

            <label class="weui-cell weui-check__label" for="s12">
                <div class="weui-cell__bd">
                    <div style="float:left;">基础保障周末班</div>
                    <div style="float:right;">￥5800</div>
                </div>
                <div class="weui-cell__ft">
                    <input type="checkbox" class="weui-check" data-id="2" name="checkbox2" id="s12"/>
                    <i class="weui-icon-checked"></i>
                </div>
            </label>-->
        </div>

        <div>
            代金券：<span id="couponMoney"></span>
        </div>
        <div>
            合计金额：<span id="totalMoney"></span>
        </div>

        <div class="weui-btn-area">
            <a class="weui-btn weui-btn_primary" href="javascript:;" id="handlerUnderline">线下报名</a>
            <a class="weui-btn weui-btn_primary" href="javascript:;" id="handlerSubmit">立即报名</a>
        </div>
    </div>

    <ul id="goods">

    </ul>
</div>

<div id="console"></div>

<script type="text/javascript">
    $(function() {

        var loading, $goods = $('#goods'),
            $handlerSubmit = $('#handlerSubmit'), $handlerUnderline = $('#handlerUnderline'),
            $list = $('#list'), $couponMoney = $('#couponMoney'), $totalMoney = $('#totalMoney');

        //获取URL中的参数(groupId,openid,mobile)
        var userId = Commons.getRequestParam('userId')
        var groupId = Commons.getRequestParam('groupId')
        var openid = Commons.getRequestParam('openid')
        var mobile = Commons.getRequestParam('mobile')
        var couponId = Commons.getRequestParam('couponId')
        var couponMoney = Commons.getRequestParam('couponMoney')

        $.ajax({
            type: 'POST',
            url: Commons.WEIXIN_OAUTH_H5_URL + '/wx/jssdk/config',
            dataType: 'JSON',
            success: function(result) {
                wx.config({
                    debug: false, 					// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: result.appid, 			// 必填，公众号的唯一标识
                    timestamp: result.timestamp, 	// 必填，生成签名的时间戳
                    nonceStr: result.noncestr, 		// 必填，生成签名的随机串
                    signature: result.signature,	// 必填，签名，见附录1
                    // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                    jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                    ]
                });

                wx.ready(function(){
                    loading = weui.loading('加载中');

                    $couponMoney.text(couponMoney)

                    //获取套餐信息
                    getGoodsGroup(groupId)

                    //立即报名
                    $handlerSubmit.click(function () {
                        handlerSubmit(userId, openid, mobile);
                    })

                    //线下报名
                    $handlerUnderline.click(function () {

                    })

                    //分享
                    share()
                });

                wx.error(function(res){
                    weui.alert('权限验证失败，jsApiList是否未配置');
                });
            },
            error: function(e, ee) {
                console.info(e);
            }
        })

        //获取套餐信息
        function getGoodsGroup(groupId) {
            $.ajax({
                type: 'get',
                url: Commons.WEIXIN_OAUTH_H5_URL + '/wx/xczs/getGoodsGroupById?goodsGroupId='+groupId,
                success: function (result) {
                    $('#groupHeader').html(result.name)
                    getGoods(result.id)
                },
                complete: function () {
                },
                error: function (data) {
                    loading.hide()
                }
            })

        }

        //获取商品信息
        function getGoods(groupId) {
            $.ajax({
                type: 'get',
                url: Commons.WEIXIN_OAUTH_H5_URL + '/wx/xczs/getGoods?goodsGroupId='+groupId,
                success: function (result) {

                    if(result.status) {

                        $.map(result.data, function (p) {
                            var label = '<label class="weui-cell weui-check__label" for="s'+p.id+'">\n' +
                                '                <div class="weui-cell__bd">\n' +
                                '                    <div style="float:left;">'+p.name+'</div>\n' +
                                '                    <div style="float:right;">￥'+p.price+'</div>\n' +
                                '                </div>\n' +
                                '                <div class="weui-cell__ft">\n' +
                                '                    <input type="checkbox" class="weui-check" data-id="'+p.id+'" data-name="'+p.name+'" data-detail="'+p.description+'" data-price="'+p.price+'" name="checkbox1" id="s'+p.id+'"/>\n' +
                                '                    <i class="weui-icon-checked"></i>\n' +
                                '                </div>\n' +
                                '            </label>';

                            $list.append(label)

                        })

                        //通过JS将复选框改为单选
                        $('input[type=checkbox]').on('click', function () {
                            $('input[type=checkbox]').prop("checked", false);
                            $(this).prop("checked", true);

                            $totalMoney.html($(this).data('price') - couponMoney) ;
                        })
                        $($('input[type=checkbox]')[0]).trigger("click");

                        loading.hide()
                    } else {
                        weui.alert(result.message);
                    }
                },
                complete: function () {

                },
                error: function (data) {
                    loading.hide()
                }
            })
        }

        //立即报名
        function handlerSubmit(userId, openid, mobile) {
            var goods = $('input[type=checkbox]:checked');
            var goodsId = goods.data('id') ;
            var goodsPrice = goods.data('price') ;
            var goodsName = goods.data('name') ;
            var detail = goods.data('detail') ;

            if(goodsId != undefined) {
                initPay(openid, mobile, goodsId, goodsName, detail, goodsPrice, userId, couponId)
            } else {
                weui.alert('请选择报名的套餐')
            }
        }

        function initPay(openid, mobile, goodsId, goodsName, detail, goodsPrice, userId, couponId) {
            loading = weui.loading('加载中');
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', initPay, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', initPay);
                    document.attachEvent('onWeixinJSBridgeReady', initPay);
                }
            } else {
                toPay(openid, mobile, goodsId, goodsName, detail, goodsPrice, userId, couponId);
            }
        }

        //调起支付
        function toPay(openid, mobile, goodsId, goodsName, goodsDetail, price, userId, couponId) {
            var data = {
                'body': goodsName,
                'detail': goodsDetail,
                //'total_fee': ((price-couponMoney) * 100),
                'total_fee': 1,
                'trade_type': 'JSAPI',
                'openid': openid,
                'mobile': mobile,
                'goodsId': goodsId,
                'couponId': couponId,
                'userId': userId
            };
            var url = Commons.WEIXIN_OAUTH_H5_URL + '/wx/pay/toPay';
            $.ajax({
                type: 'POST',
                url: url,
                dataType: 'JSON',
                data: data,
                success: function (result) {
                    if(result.status) {
                        var order = result.order;
                        var appId = result.appId;
                        var timeStamp = result.timeStamp;
                        var nonceStr = result.nonceStr;
                        var packages = result.package;
                        var signType = result.signType;
                        var paySign = result.paySign;

                        loading.hide()
                        //调起支付
                        onBridgeReady(appId, timeStamp, nonceStr, packages, signType, paySign)
                    } else {
                        loading.hide()
                        weui.alert("发生错误："+result.msg);
                    }

                },
                error: function (e, ee) {
                    weui.alert("系统出错，请联系系统运营商");
                }
            })
        }

        /**
         * 调起支付
         * @param appId         公众号id
         * @param timeStamp     时间戳
         * @param nonceStr      随机字符串
         * @param packages      订单详情扩展字符串(prepay_id=123456789)
         * @param signType      签名方式(MD5)
         * @param paySign       签名
         */
        function onBridgeReady(appId, timeStamp, nonceStr, packages, signType, paySign) {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId": appId,
                    "timeStamp": timeStamp,
                    "nonceStr": nonceStr,
                    "package": packages,
                    "signType": signType,
                    "paySign": paySign
                },
                function (res) {

                    // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                    if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                        weui.alert("支付成功");
                    }else if(res.err_msg == "get_brand_wcpay_request:cancel" ) {
                        //weui.alert("用户取消");
                        loading.hide()
                    }
                }
            );
        }

        //分享
        function share() {
            var shareLink = Commons.WEIXIN_OAUTH_H5_URL + '/h5/xczs/biz/goods_group.html';

            //分享到朋友圈
            wx.onMenuShareTimeline({
                title: '邀请好友一起来学车', // 分享标题
                link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: 'http://image.bitauto.com/dealer/brandgroup/m/529.png', // 分享图标
                success: function () {
                    // 用户确认分享后执行的回调函数
                    weui.toast('用户分享到朋友圈')
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });

            //分享给朋友
            wx.onMenuShareAppMessage({
                title: '邀请好友一起来学车', // 分享标题
                desc: '新用户注册即可获赠1亿越南盾用车劵，心动不与行动，赶紧注册领取！', // 分享描述
                link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: 'http://image.bitauto.com/dealer/brandgroup/m/529.png', // 分享图标
                type: 'link', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                    weui.toast('用户分享给朋友')
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
        }

        function print() {
            for(var i=0; i<arguments.length; i++) {
                $('#console').append(JSON.stringify(arguments[i])).append("<br>")
            }
        }

    });

</script>


</body>
</html>